<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElCol,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElTag 
} from 'element-plus'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { saveTableApi, delTableListApi } from '@/api/table'
import {
  getListApi,
  changeStatusApi,
  finishOrderApi,
  updateWorkInfoApi,
  changeNotifyApi,
  businessChangeApi,
  cancelNotifyApi 
} from '@/api/order'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive, h } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'selection',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     hidden: true
  //   },
  //   table: {
  //     type: 'selection'
  //   }
  // },
  // {
  //   field: 'index',
  //   label: t('tableDemo.index'),
  //   type: 'index',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     hidden: true
  //   }
  // },
  {
    field: 'expand',
    type: 'expand',
    path: 'hidden',
    slots: {
      default: (data: TableSlotDefault) => {
        const { row } = data
        const obj = JSON.parse(row.userAddress)
        const workerStatusName = h(ElTag,{
        type:
            row.workerStatus === 1 ? 'success' : 'info'
        },()=> row.workerStatus === 1 ? '结算' : '未结算')
        return (
          <ElRow>
            <ElCol span={8}>
              <div class="ml-6">
                <div>预约人：{row.userName}</div>
                <div> 预约电话：{row.userPhone}</div>
                <div>预约地址：{obj.receiver_address}</div>
                <div style="color:red">用户备注：{row.userContent}</div>
              </div>
            </ElCol>
            <ElCol span={4}>
              <div class="ml-6">
                <div>服务人员：{row.workerName}</div>
                <div> 结算金额：{row.workerPrice + ' 好评金额：' + row.workerGoodPrice}</div>
                <div>结算状态：{workerStatusName}</div>
            </div>
            </ElCol>
            <ElCol span={6}>
              {
                (row.bookStatus !== 1 && row.bookStatus !== 3) ? <BaseButton type="primary" onClick={()=>updateWorkerDialog(row)}>派单</BaseButton> : ''
              }
              {
                row.bookStatus === 2 ? <BaseButton type="info" onClick={()=>businessChangeDialog(row)}>商家改约</BaseButton> : ''
              }
            </ElCol>
          </ElRow>
        )
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'userPhone',
    label: t('order.userPhone'),
    search: {
      component: 'Input'
    },
    hidden: true,
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  // {
  //   field: 'id',
  //   label: t('order.id'),
  //   search: {
  //     component: 'Input'
  //   },
  //   detail: {
  //     span: 24
  //   }
  // },
  {
    field: 'orderId',
    label: t('order.orderId'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'productName',
    minWidth:150,
    label: t('order.productName'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'bookStatus',
    label: t('order.bookStatus'),
    width: 100,
    search: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        },
        options: [
          {
            label: '待接单',
            value: 1
          },
          {
            label: '已接单',
            value: 2
          },
          {
            label: '订单取消',
            value: 3
          },
          {
            label: '商家已完成',
            value: 5
          },
          {
            label: '已完成',
            value: 6
          },
          {
            label: '订单改约',
            value: 7
          },
          {
            label: '未结算',
            value: 8
          },
          {
            label: '未派单',
            value: 9
          }
        ]
      }
    },
    detail: {
      span: 24
    },
    formatter: (_: Recordable, __: TableColumn, cellValue: number) => {
      return h(
        ElTag,
        {
          type:
            cellValue === 1
              ? 'warning'
              : cellValue === 2
                ? 'primary'
                : cellValue === 3
                  ? 'danger'
                  : cellValue === 5
                    ? 'info'
                    : cellValue === 7
                      ? 'danger'
                      : 'success'
        },
        () =>
          cellValue === 1
            ? '待接单'
            : cellValue === 2
              ? '已接单'
              : cellValue === 3
                ? '已取消'
                : cellValue === 5
                  ? '商家已完成'
                  : cellValue === 7
                    ? '商家取消'
                    : '已完成'
      )
    }
  },
  {
    field: 'beginTime',
    width:150,
    label: t('order.beginTime'),
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'amount',
    label: t('order.amount'),
    width:100,
    search: {
      hidden: true
    },
    detail: {
      span: 14
    }
  },
  {
    field: 'createTime',
    label: t('order.createTime'),
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  // {
  //   field: 'userContent',
  //   label: t('order.userContent'),
  //   search: {
  //     hidden: true
  //   },
  //   detail: {
  //     span: 14
  //   }
  // },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              {data.row.bookStatus === 1 
                ? <><BaseButton type="success" onClick={()=>updateStatus(data.row, 2)}>接单</BaseButton><BaseButton type="danger" onClick={()=>updateStatus(data.row, 3)}>拒单</BaseButton></>
                : (data.row.bookStatus === 2 && data.row.workerNmae != "")
                  ? <BaseButton type="info" onClick={()=>finishOrder(data.row)}>完成</BaseButton>
                  : (data.row.bookStatus === 2 && data.row.reserveStatus===1)
                    ? <><BaseButton type="warning" onClick={()=>changeNotify(data.row, 2)}>同意改约</BaseButton><BaseButton type="danger" onClick={()=>changeNotify(data.row, 3)}>拒绝改约</BaseButton></>
                    : data.row.bookStatus === 2 ? <BaseButton type="danger" onClick={()=>cancelNotifyDialog(data.row)}>取消订单</BaseButton> :''
              }
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const businessChangeFlag = ref(false)
const businessChangeDate = ref('')
const updateWorkerFlag = ref(false)
const dialogTitle = ref('')

const cancelNotifyFlag = ref(false)
const cancelNotifyText = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const schema = reactive<FormSchema[]>([
  {
    field: 'workerName',
    label: '服务人员',
    component: 'Input'
  },
  {
    field: 'workerPrice',
    label: '结算金额',
    component: 'Input'
  },
  {
    field: 'workerGoodPrice',
    label: '好评金额',
    component: 'Input'
  },
  {
    field: 'workerStatus',
    label: '结算状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '未结算',
          value: 0
        },
        {
          label: '已结算',
          value: 1
        }
      ]
    }
  }
])
const { formRegister, formMethods } = useForm()
const { getFormData, setValues } = formMethods

// const AddAction = () => {
//   dialogTitle.value = t('exampleDemo.add')
//   currentRow.value = null
//   dialogVisible.value = true
//   actionType.value = ''
// }

// const delLoading = ref(false)

// const delData = async (row: TableData | null) => {
//   const elTableExpose = await getElTableExpose()
//   ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
//   delLoading.value = true
//   await delList(unref(ids).length).finally(() => {
//     delLoading.value = false
//   })
// }

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const updateStatus = async (data: any | null, bookStatus: any) => {
  const { id } = data
  const res = await changeStatusApi({
    id: unref(id),
    bookStatus: unref(bookStatus)
  })
  console.log(res)
  getList()
}

const changeNotify = async (data: any | null, bookStatus: any) => {
  const { id } = data
  const res = await changeNotifyApi({
    id: unref(id),
    changeOrderResult: unref(bookStatus)
  })
  console.log(res)
  getList()
}

const finishOrder = async (data: any | null) => {
  const { id } = data
  const res = await finishOrderApi({
    id: unref(id)
  })
  console.log(res)
  getList()
}

const saveCancelNotify = async () => {
  saveLoading.value = true
  const { id } = currentRow.value
  const res = await cancelNotifyApi({
    id: unref(id),
    cancelReason: cancelNotifyText.value
  })
  cancelNotifyFlag.value = false
  saveLoading.value = false
  console.log(res)
  getList()
}

const businessChangeDialog = (row: any) => {
  businessChangeFlag.value = true
  currentRow.value = row
  businessChangeDate.value = ''
}

const cancelNotifyDialog = (row: any) => {
  cancelNotifyFlag.value = true
  currentRow.value = row
  cancelNotifyText.value = ''
}

const updateWorkerDialog = (row: any) => {
  updateWorkerFlag.value = true
  currentRow.value = row
  setValues({
    workerName: row.workerName,
    workerPrice: row.workerPrice,
    workerGoodPrice: row.workerGoodPrice,
    workerStatus: row.workerStatus
  })
}

const saveBusinessChangeDate = async () => {
  saveLoading.value = true
  const { id } = currentRow.value
  console.log(businessChangeDate)
  const res = await businessChangeApi({ id: unref(id), endTimeString: businessChangeDate.value })
  businessChangeFlag.value = false
  saveLoading.value = false
  console.log(res)
  getList()
}

const saveUpdateWorker = async () => {
  saveLoading.value = true
  const data = await getFormData()
  data.id = currentRow.value.id
  const res = await updateWorkInfoApi(data)
  console.log(res)
  saveLoading.value = false
  updateWorkerFlag.value = false
  getList()
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <!-- <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton>
    </div> -->

    <Table
      default-expand-all
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      size="small"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>

  <ElDialog v-model="businessChangeFlag" title="商家改约" width="30%">
    <ElForm>
      <ElFormItem label="团单名称">
        <ElInput :model-value="currentRow.productName" disabled="true"></ElInput>
      </ElFormItem>
      <ElFormItem label="预约地址">
        <ElInput :model-value="currentRow.userAddress" type="textarea" disabled="true"></ElInput>
      </ElFormItem>
      <ElFormItem label="预约时间">
        <ElInput :model-value="currentRow.beginTime" disabled="true"></ElInput>
      </ElFormItem>
      <ElFormItem label="预约时间">
        <ElDatePicker
          v-model="businessChangeDate"
          type="datetime"
          placeholder="选择更约的时间"
          :default-time="currentRow.beginTime"
          format="YYYY-MM-DD·HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <BaseButton
        type="primary"
        :loading="saveLoading"
        @click="saveBusinessChangeDate"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="businessChangeFlag = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </ElDialog>
  <ElDialog v-model="cancelNotifyFlag" title="商家取消" width="30%">
    <div>
      <ElFormItem label="团单名称">
        <ElInput :model-value="currentRow.productName" :disabled="true"></ElInput>
      </ElFormItem>
      <ElFormItem label="预约地址">
        <ElInput :model-value="currentRow.userAddress" type="textarea" :disabled="true"></ElInput>
      </ElFormItem>
      <ElFormItem label="预约时间">
        <ElInput :model-value="currentRow.beginTime" :disabled="true"></ElInput>
      </ElFormItem>
      <ElFormItem label="取消原因">
        <ElInput :model-value="cancelNotifyText" />
      </ElFormItem>
    </div>
    <template #footer>
      <BaseButton type="danger" :loading="saveLoading" @click="saveCancelNotify">
        确认取消
      </BaseButton>
      <BaseButton @click="cancelNotifyFlag = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </ElDialog>

  <ElDialog v-model="updateWorkerFlag" title="派单" width="30%">
    <Form :schema="schema" @register="formRegister" />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="saveUpdateWorker">
        确认
      </BaseButton>
      <BaseButton @click="updateWorkerFlag = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </ElDialog>
</template>
